//
//  JEHRootCollectionViewCell.m
//  SinaNews
//
//  Created by 蒋恩浩 on 15/12/1.
//  Copyright © 2015年 JEH. All rights reserved.
//

#import "JEHRootCollectionViewCell.h"

#define kCarouselViewHeight 200
#define kCellHeight 100
#define kThreePicHeight 170

@interface JEHRootCollectionViewCell ()<UITableViewDataSource, UITableViewDelegate, presentViewController1>

@property (nonatomic, retain) NSMutableArray *dataSource;

@end

@implementation JEHRootCollectionViewCell

- (void)dealloc
{
    [_titleUrl release];
    [_tableView release];
    [_dataSource release];
    [super dealloc];
}

- (void)getData {
    
    UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    indicator.center = self.center;
    indicator.color = [UIColor magentaColor];
    [indicator startAnimating];
    [self.tableView addSubview:indicator];
    
    if (_titleUrl) {

        self.dataSource = [NSMutableArray arrayWithCapacity:0];
        [JEHNetWorkTool getWithUrl:self.titleUrl parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {

            if (result) {

                NSDictionary *dictionary = result[@"data"];
                NSArray *array = dictionary[@"list"];
                for (NSDictionary *dictionary in array) {
                    
                    JEHRootModel *rootModel = [[JEHRootModel alloc] initWithDictionary:dictionary];
                    [self.dataSource addObject:rootModel];
                    [rootModel release];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                    [self addHeaderRefresh];
                    [self addFooterRefresh];
                    [indicator stopAnimating];
                });
            } else {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请检查网络" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [alert dismissWithClickedButtonIndex:0 animated:NO];
                });
                [alert release];
            }
        } fail:^(NSError *error) {
            [indicator stopAnimating];
            NSLog(@"没有网");
        }];
    }
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self createTableView];
    }
    return self;
}

- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    [super applyLayoutAttributes:layoutAttributes];
    self.tableView.frame = self.bounds;
}

- (void)setTitleUrl:(NSString *)titleUrl {
    if (_titleUrl != titleUrl) {
        [_titleUrl release];
        _titleUrl = [titleUrl retain];
        [self.tableView reloadData];
        [self getData];
    }
}

#pragma mark - createTableView
- (void)createTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView nightMode];
    [_tableView registerClass:[JEHNewsTableViewCell class] forCellReuseIdentifier:@"JEHNewsTableViewCellIdentifier"];
    [_tableView registerClass:[JEHCarouselTableViewCell class] forCellReuseIdentifier:@"JEHCarouselTableViewCellIdentifier"];
    [_tableView registerClass:[JEHThreePicTableViewCell class] forCellReuseIdentifier:@"JEHThreePicTableViewCellIdentifier"];
    
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"A"];
    [self addSubview:self.tableView];
}

#pragma mark - refresh
- (void)addHeaderRefresh {
    
    [_tableView addHeaderWithCallback:^{
        // 当进入刷新状态后回调这个block
        
        // 模拟延迟加载数据，因此2秒后才调用
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self getData];
            
            // tableView刷新列表
            [_tableView reloadData];
            // 刷新完成后结束header的刷新状态
            [_tableView headerEndRefreshing];
        });
    }];
}

- (void)addFooterRefresh {
    
        __block int number;
        [_tableView addFooterWithCallback:^{
            // 当进入刷新状态后回调这个block
            
            NSString *newUrl = [self.titleUrl stringByReplacingOccurrencesOfString:@"pull_times=5" withString:[NSString stringWithFormat:@"pull_times=%d", number++]];
            [JEHNetWorkTool getWithUrl:newUrl parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
                
                if (number == 6) {
                    
                    number = 0;
                }
                if (result) {
                    
                    NSDictionary *dictionary = result[@"data"];
                    NSArray *array = dictionary[@"list"];
                    for (NSDictionary *dictionary in array) {
                        
                        JEHRootModel *rootModel = [[JEHRootModel alloc] initWithDictionary:dictionary];
                        [self.dataSource addObject:rootModel];
                        [rootModel release];
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.tableView reloadData];
                        [_tableView footerEndRefreshing];
                    });
                }
            } fail:^(NSError *error) {
                NSLog(@"网不好¬¬¬¬等会");
            }];
        
//         模拟延迟加载数据，因此2秒后才调用
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//
//              [_tableView footerEndRefreshing];
//        });
        }];
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (_dataSource) {
        
        if ([self.titleUrl isEqualToString:kAutomobilesGETURL]) {
            
            return self.dataSource.count - 5;
        } else if ([self.titleUrl isEqualToString:kTechnologyGETURL]) {
            
            return self.dataSource.count - 5;
        } else if ([self.titleUrl isEqualToString:kHeadlineGETURL] || [self.titleUrl isEqualToString:kEntertainmentGETURL] || [self.titleUrl isEqualToString:kSportsGETURL] || [self.titleUrl isEqualToString:kLiaoningGETURL] || [self.titleUrl isEqualToString:kFinanceGETURL]) {
            return self.dataSource.count - 6;
        } else {
            return self.dataSource.count;
        }
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_dataSource.count) {
    
        if ([self.titleUrl hasSuffix:@"toutiao"] || [self.titleUrl hasSuffix:@"ent"] || [self.titleUrl hasSuffix:@"sports"] || [self.titleUrl hasSuffix:@"liaoning"] || [self.titleUrl hasSuffix:@"finance"]) {
            
            if (indexPath.row == 0) {
                
                JEHCarouselTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JEHCarouselTableViewCellIdentifier"];
                NSMutableArray *picture = [NSMutableArray arrayWithCapacity:0];
                NSMutableArray *title = [NSMutableArray arrayWithCapacity:0];
                for (int i = 0; i < 5; i++) {
                    
                    JEHRootModel *root = self.dataSource[i];
                    if (root.kpic) {
                        
                        [picture addObject:root.kpic];
                        [title addObject:root.title];
                    }
                }
                cell.picArray = picture;
                cell.titleArray = title;
                cell.carousel.delegate = self;
                return cell;
            } else {
                
                JEHRootModel *root = self.dataSource[indexPath.row + 4];
                JEHNewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JEHNewsTableViewCellIdentifier"];
                if ([root.category isEqualToString:@"hdpic"]) {
                    
                    JEHThreePicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JEHThreePicTableViewCellIdentifier"];
                    cell.rootModel = root;
                    [cell nightMode];
                    [cell.titleLabel nightMode];
                    return cell;
                } else {
                    cell.rootModel = root;
                    [cell nightMode];
                    [cell.titleLabel nightMode];
                    return cell;
                }
            }
        } else if ([self.titleUrl hasSuffix:@"auto"]) {

            if (indexPath.row == 0) {
                
                JEHCarouselTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JEHCarouselTableViewCellIdentifier"];
                NSMutableArray *picture = [NSMutableArray arrayWithCapacity:0];
                NSMutableArray *title = [NSMutableArray arrayWithCapacity:0];
                for (int i = 0; i < 4; i++) {
                    
                    JEHRootModel *root = self.dataSource[i];
                    [picture addObject:root.kpic];
                    [title addObject:root.title];
                }
                cell.picArray = picture;
                cell.titleArray = title;
                return cell;
            } else {
                JEHRootModel *root = self.dataSource[indexPath.row + 3];
                JEHNewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JEHNewsTableViewCellIdentifier"];
                if ([root.category isEqualToString:@"hdpic"]) {
                    
                    JEHThreePicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JEHThreePicTableViewCellIdentifier"];
                    [cell nightMode];
                    [cell.titleLabel nightMode];
                    cell.rootModel = root;
                    return cell;
                } else {
                    [cell nightMode];
                    [cell.titleLabel nightMode];
                    cell.rootModel = root;
                    return cell;
                }
            }
        } else if ([self.titleUrl hasSuffix:@"tech"]) {
            
            if (indexPath.row == 0) {
                
                JEHCarouselTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JEHCarouselTableViewCellIdentifier"];
                NSMutableArray *picture = [NSMutableArray arrayWithCapacity:0];
                NSMutableArray *title = [NSMutableArray arrayWithCapacity:0];
                for (int i = 0; i < 2; i++) {
                    
                    JEHRootModel *root = self.dataSource[i];
                    [picture addObject:root.kpic];
                    [title addObject:root.title];
                }
                cell.picArray = picture;
                cell.titleArray = title;
                return cell;
            } else {
                JEHRootModel *root = self.dataSource[indexPath.row + 1];
                JEHNewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JEHNewsTableViewCellIdentifier"];
                if ([root.category isEqualToString:@"hdpic"]) {
                    
                    JEHThreePicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JEHThreePicTableViewCellIdentifier"];
                    [cell nightMode];
                    [cell.titleLabel nightMode];
                    cell.rootModel = root;
                    return cell;
                } else {
                    [cell nightMode];
                    [cell.titleLabel nightMode];
                    cell.rootModel = root;
                    return cell;
                }
            }
        } else {
            JEHRootModel *root = self.dataSource[indexPath.row];
            JEHNewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JEHNewsTableViewCellIdentifier"];
            [cell nightMode];
            [cell.titleLabel nightMode];
            cell.rootModel = root;
            return cell;
        }
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"A"];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    JEHRootModel *root = nil;
    if ([self.titleUrl isEqualToString:kAutomobilesGETURL] && indexPath.row + 3 < self.dataSource.count) {
        
        if (indexPath.row == 0) {
            
            root = self.dataSource[indexPath.row];
            return kCarouselViewHeight;
        } else {
            root = self.dataSource[indexPath.row + 3];
            if ([root.category isEqualToString:@"hdpic"]) {
                
                return kThreePicHeight;
            } else {
                return kCellHeight;
            }
        }
    } else if ([self.titleUrl isEqualToString:kTechnologyGETURL] && indexPath.row + 1 < self.dataSource.count) {
        
        if (indexPath.row == 0) {
            
            return kCarouselViewHeight;
        } else {
            root = self.dataSource[indexPath.row + 1];
            if ([root.category isEqualToString:@"hdpic"]) {
                
                return kThreePicHeight;
            } else {
                return kCellHeight;
            }
        }
    } else if (([self.titleUrl isEqualToString:kHeadlineGETURL] || [self.titleUrl isEqualToString:kEntertainmentGETURL] || [self.titleUrl isEqualToString:kSportsGETURL] || [self.titleUrl isEqualToString:kLiaoningGETURL] || [self.titleUrl isEqualToString:kFinanceGETURL]) && indexPath.row + 4 < self.dataSource.count) {
        
        if (indexPath.row == 0) {
            
            return kCarouselViewHeight;
        } else {
            root = self.dataSource[indexPath.row + 4];
            if ([root.category isEqualToString:@"hdpic"]) {
                
                return kThreePicHeight;
            } else {
                return kCellHeight;
            }
        }
    } else {
        return kCellHeight;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
    JEHRootModel *root = nil;
    if ([self.titleUrl isEqualToString:kAutomobilesGETURL]) {
        
        root = self.dataSource[indexPath.row + 3];
    } else if ([self.titleUrl isEqualToString:kTechnologyGETURL]) {
        
        root = self.dataSource[indexPath.row + 1];
    } else if ([self.titleUrl isEqualToString:kHeadlineGETURL] || [self.titleUrl isEqualToString:kEntertainmentGETURL] || [self.titleUrl isEqualToString:kSportsGETURL] || [self.titleUrl isEqualToString:kLiaoningGETURL] || [self.titleUrl isEqualToString:kFinanceGETURL]) {
        
        root = self.dataSource[indexPath.row + 4];
    } else {
        root = self.dataSource[indexPath.row];
    }
    if ([root.category isEqualToString:@"hdpic"]) {
        
        [self.delegate passRootModelToDetail:root];
    } else if ([root.category isEqualToString:@"video"]) {
        
        [self.delegate passRootModelToPlayerVC:root];
    } else {
        [self.delegate passRootModelToWebView:root];
    }
}


#pragma mark - presentViewController
- (void)presentViewController1WithTemp:(NSInteger)temp {
    
    JEHRootModel *rootModel = self.dataSource[temp];
    [self.delegate passRootModelToDetail:rootModel];
}

@end












